package net.zdreamer.geracomium.ui.login;

import android.app.Activity;
import android.app.Dialog;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.example.geracomium.R;

import net.zdreamer.geracomium.constant.Constant;
import net.zdreamer.geracomium.myviews.CustomProgressDialog;
import net.zdreamer.geracomium.utils.account.LoginService;
import net.zdreamer.geracomium.utils.tools_utils.BCrypt;
import net.zdreamer.geracomium.utils.tools_utils.URLTools;

import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import cn.smssdk.EventHandler;
import cn.smssdk.SMSSDK;

/**
 * Created by xuhaitao on 15/1/7.
 */
public abstract class RegistBase extends Activity implements View.OnClickListener {
    public static final int GET_SUCCEED = 0x00000001;/*请求验证码成功*/
    public static final int GET_FAILED = 0x00000000;/*请求验证码失败*/
    public static final int VERIFY_SUCCEED = 0x00000011;/*验证通过*/
    public static final int VERIFY_FAILED = 0x00000010;/*验证失败*/

    protected String phoneNum, realPhoneNum, username, password, comfirmPassword;
    protected Activity activity;
    protected EditText et_userName, et_password, et_confirmPassword, et_phoneNum, et_verificationCode;
    private Dialog lodingdialog;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_regist_accout);
        lodingdialog= CustomProgressDialog.createLoadingDialog(RegistBase.this, "请稍后");
    }

    /**
     * 获取验证码
     */
    protected void getVerification() {
        phoneNum = et_phoneNum.getText().toString().trim();
        if (null == phoneNum || "".equals(phoneNum)) {
            Toast.makeText(activity, "手机号码不能为空", Toast.LENGTH_SHORT).show();
        } else if (!isMobileNum(phoneNum)) {
            Toast.makeText(activity, "手机号格式错误", Toast.LENGTH_SHORT).show();
        } else {
            if (activity instanceof RegistActivity) {
                if (isRegisted(phoneNum)) {
                    return;
                }
            } else {
                if (!isRegisted(phoneNum)) {
                    return;
                }
            }
            SMSSDK.getVerificationCode("86", phoneNum);
        }
    }

    /**
     * 短信验证
     */
    protected void SMSCheck() {
        String veryfyNum = et_verificationCode.getText().toString().trim();
        if (null == realPhoneNum || "".equals(realPhoneNum)) {
            Toast.makeText(activity, "请先获取验证码", Toast.LENGTH_SHORT).show();
        } else if (!et_phoneNum.getText().toString().trim().equals(realPhoneNum)) {
            Toast.makeText(activity, "请输入正确的手机号", Toast.LENGTH_SHORT).show();
        } else {
            if (null == veryfyNum || "".equals(veryfyNum)) {
                Toast.makeText(activity, "验证码不能为空", Toast.LENGTH_SHORT).show();
            } else {
                SMSSDK.submitVerificationCode("86", phoneNum, veryfyNum);
            }
        }
    }

    /**
     * 向服务器提交数据
     */
    public void Submit() {
        username = et_userName.getText().toString().trim();
        password = et_password.getText().toString().trim();
        comfirmPassword = et_confirmPassword.getText().toString().trim();
        Map<String, String> map = new HashMap<String, String>();
        if (username == null || username.equals("")) {
            Toast.makeText(activity, "用户名不能为空", Toast.LENGTH_SHORT).show();
        }else if (username.length()<5||username.length()>13){
            Toast.makeText(activity, "用户名在6到12位", Toast.LENGTH_SHORT).show();
        }else if (password == null || password.equals("")) {
            Toast.makeText(activity, "密码不能为空", Toast.LENGTH_SHORT).show();
        } else if (!password.equals(comfirmPassword)) {
            Toast.makeText(activity, "重复密码和密码不一致，请重新输入密码", Toast.LENGTH_SHORT).show();
        } else {
         //   String URLPath = URLTools.LogInUrl + "userAccounts?apiKey=a968f6e8-9265-4be6-b61a-3a29395be89b";
            LoginService.RegistPost(username, password, phoneNum, URLTools.RegistUrl,handler);
            lodingdialog.show();
        }
    }
    private final Handler handler = new Handler() {
        @Override
        public void handleMessage(android.os.Message msg) {
            switch (msg.arg1) {
                case 0:
                    Toast.makeText(activity, "注册失败", Toast.LENGTH_SHORT).show();
                    lodingdialog.dismiss();
                    break;
                case 201:
                    SMSCheck();
                    lodingdialog.dismiss();
                    break;
                case 409:
                    Toast.makeText(activity, "该用户已存在", Toast.LENGTH_SHORT).show();
                    lodingdialog.dismiss();
                    break;
                case 400:
                    Toast.makeText(activity, "请填写完整信息", Toast.LENGTH_SHORT).show();
                    lodingdialog.dismiss();
                    break;
                default:
                    break;
            }
        };
    };
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.verify_accomplish:

                Submit();
                break;
            case R.id.get_time:
                getVerification();
                break;
        }
    }

    protected void initViews(final Activity activity) {
        this.activity = activity;
        et_userName = (EditText) activity.findViewById(R.id.regist_username);
        et_password = (EditText) activity.findViewById(R.id.regist_password);
        et_confirmPassword = (EditText) activity.findViewById(R.id.regist_confirm_password);
        et_phoneNum = (EditText) activity.findViewById(R.id.verify_number);
        et_verificationCode = (EditText) activity.findViewById(R.id.verify_testnumber);
        activity.findViewById(R.id.get_time).setOnClickListener(this);
        activity.findViewById(R.id.verify_accomplish).setOnClickListener(this);
        ((TextView) activity.findViewById(R.id.title_content)).setText(activity instanceof RegistActivity ? "注册账户" : "密码找回");
        ((TextView) activity.findViewById(R.id.newpwd)).setText(activity instanceof RegistActivity ? "密码" : "新密码");
        activity.findViewById(R.id.share).setVisibility(View.GONE);
        activity.findViewById(R.id.back).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                activity.finish();
            }
        });
        SMSSDK.initSDK(activity, Constant.SMS_APP_KEY, Constant.SMS_APP_SECRET);
        EventHandler handler = new EventHandler() {
            public void afterEvent(int event, int result, Object data) {
                if (event == SMSSDK.EVENT_SUBMIT_VERIFICATION_CODE) {
                    // 提交验证码
                    afterSubmit(result, data);
                } else if (event == SMSSDK.EVENT_GET_VERIFICATION_CODE) {
                    // 获取验证码成功后的执行动作
                    afterGet(result, data);
                }
            }
        };
        SMSSDK.registerEventHandler(handler);
    }

    protected abstract void afterGet(int result, Object data);

    protected abstract void afterSubmit(int result, Object data);

    /**
     * 判断是否为手机号码
     *
     * @param mobiles
     * @return
     */
    public boolean isMobileNum(String mobiles) {
        Pattern p = Pattern.compile("^((13[0-9])|(15[^4,\\D])|177|(18[0-3,5-9]))\\d{8}$");
        Matcher m = p.matcher(mobiles);
        return m.matches();
    }

    /**
     * 判断手机号是否注册过
     *
     * @param phoneNum
     * @return
     */
    private boolean isRegisted(String phoneNum) {
        return false;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        SMSSDK.unregisterAllEventHandler();
    }

    class MyCount extends CountDownTimer {
        public MyCount(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onFinish() {
            ((TextView) activity.findViewById(R.id.get_time)).setText("重新获取");
            activity.findViewById(R.id.get_time).setClickable(true);
        }

        @Override
        public void onTick(long millisUntilFinished) {
            ((TextView) activity.findViewById(R.id.get_time)).setText("请等待60秒(" + millisUntilFinished / 1000 + ")...");
            activity.findViewById(R.id.get_time).setClickable(false);
        }
    }

}